package com.mby.utils;

import com.mby.entity.BaseModel;
import com.mby.entity.Sequence;
import com.mby.entity.User;
import com.mongodb.WriteResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;

/**
 * Created by noah on 2017/8/14.
 */

@Service
public class MongoTools {

    @Autowired
    public MongoTemplate mongoTemplate;

    //查找并更新
    public <T> T findAndUpdate(String update_str,String where_str,Class<T> class_name){
        try{
            Query query = MongoUtil.getQuery(where_str,null,null);
            Update update = MongoUtil.getUpdate(update_str);
            return mongoTemplate.findAndModify(query,update,new FindAndModifyOptions().returnNew(true).upsert(true),class_name);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查找并更新
    public <T> T findAndUpdate(BaseModel model,String where_str,Class<T> class_name){
        try{
            Query query = MongoUtil.getQuery(where_str,null,null);
            Update update = MongoUtil.getUpdateByModel(model);
            return mongoTemplate.findAndModify(query,update,new FindAndModifyOptions().returnNew(true).upsert(true),class_name);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查询多条记录,并指定返回字段
    public List<?> findMany(String inc_str,String where_str,String sort_str,Class<?> class_name){
        try{
            Query query  = MongoUtil.getQuery(where_str,sort_str,inc_str);
            return mongoTemplate.find(query,class_name);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查询多条记录
    public List<?> findMany(String where_str,String sort_str,Class<?> class_name){
        try{
            Query query  = MongoUtil.getQuery(where_str,sort_str,null);
            return mongoTemplate.find(query,class_name);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查询多条记录
    public List<?> findMany(BaseModel model,String sort_str,Class<?> class_name){
        try{
            Query query  = MongoUtil.getQuery(model,sort_str,null);
            return mongoTemplate.find(query,class_name);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //统计数据
    public long count(String where_str,Class<?> class_name){
        Query query  = MongoUtil.getQuery(where_str,null,null);
        return mongoTemplate.count(query,class_name);
    }

    //新增一条记录
    public BaseModel addOne(BaseModel model){
        model.setId(getAutoIncreaseID(model.getClass().getName()));
        model.setCreatedAt(new Date());
        model.setDeleted(false);
        User u = (User) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        if(u != null){
            model.setCreatedBy(u.getId());
        }
        mongoTemplate.save(model);
        return model;
    }

    //新增一条记录
    public Object addOne(Object obj){
        mongoTemplate.save(obj);
        return obj;
    }

    //查询一条记录
    public <T> T findOne(String inc_str,String where_str,Class<T> class_name){
        try{
            Query query = MongoUtil.getQuery(where_str,null,inc_str);
            return  mongoTemplate.findOne(query, class_name);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //根据实体类对多个字段执行更新
    public void update(BaseModel model,String where_str,Class<?> class_name){
        try{
            Query query = MongoUtil.getQuery(where_str,null,null);
            Update update = MongoUtil.getUpdateByModel(model);
            if(!update.equals(new Update())){
                mongoTemplate.updateFirst(query, update, class_name);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //执行更新
    public void update(String update_str,String where_str,Class<?> class_name){
        try{
            Query query = MongoUtil.getQuery(where_str,null,null);
            Update update = MongoUtil.getUpdate(update_str);
            mongoTemplate.updateFirst(query, update, class_name);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //通过where删除
    public Boolean delete(String where_str,Class<?> class_name){
        Boolean flag = false;
        try{
            Query query = MongoUtil.getQuery(where_str,null,null);
            WriteResult wrt = mongoTemplate.remove(query,class_name);
            flag =  wrt.getN()>0?true:false;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    public Integer getAutoIncreaseID(String sequence_name){
        Sequence sequence = findAndUpdate("{'sequenceNext+':1}", "{'id':'"+sequence_name+"'}",Sequence.class);
        return sequence.getSequenceNext();
    }
}
